<template>
  <el-dialog title="收货地址" :visible.sync="show" class="register" width="600px" :show-close="false">
    <div slot="title" class="top">用户注册</div>
    <el-form :model="form" label-width="87px" :rules="rules" ref="form">
      <!-- 头像上传 -->
      <el-form-item label="头像" prop="avatar">
        <el-upload
          class="avatar-uploader"
          :action="baseURL + '/uploads'"
          name="image"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt />
        </el-dialog>
      </el-form-item>
      <el-form-item label="昵称" prop="username">
        <el-input v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email"></el-input>
      </el-form-item>
      <el-form-item label="手机" prop="phone">
        <el-input v-model="form.phone"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" show-password></el-input>
      </el-form-item>
      <el-form-item label="图形码" prop="code">
        <el-row class="row">
          <el-col :span="16">
            <el-input v-model="form.code"></el-input>
          </el-col>
          <el-col :span="7" :offset="1">
            <img @click='refresh' :src="codeImg" class="img" alt />
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="验证码" prop="rcode">
        <el-row>
          <el-col :span="16" >
            <el-input v-model="form.rcode"></el-input>
          </el-col>
          <el-col :span="7" :offset="1">
            <el-button @click="getCode" :disabled="totalTime<60">
              <span v-if='totalTime < 60'>{{totalTime}}秒后再次获取</span>
              <span v-else>获取用户验证码</span>              
            </el-button>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="show = false">取 消</el-button>
      <el-button type="primary" @click="toRegister">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { sendsms,register } from '@/api/login.js'
export default {
  data() {
    return {
      show: false,
      dialogImageUrl: "",
      dialogVisible: false,
      disabled: false,
      imageUrl: "",
      baseURL:process.env.VUE_APP_URL,
      codeImg:process.env.VUE_APP_URL + '/captcha?type=sendsms',
      totalTime:60,
      form: {
        username: "", //用户名
        email: "", //邮箱
        phone: "", //手机号
        password: "",//密码
        rcode: "",//短信验证码
        code: "",//图形码
        avatar:'',//头像地址
      },
      rules: {
        avatar:[{ required: true, message: "请上传头像", trigger: "change" }],
        username: [{ required: true, message: "请输入昵称", trigger: "blur" }],
        email: [{ required: true, message: "请输入邮箱", trigger: "blur" },
                {validator:(rule,value,callback)=>{
                  let reg=/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/
                  if(reg.test(value)){
                    callback()
                  }else{
                    callback('请输入正确的邮箱地址')
                  }
                },trigger:'blur'}
        ],
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {validator:(rule,value,callback)=>{
            let reg=/^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
            if (reg.test(value)){
              callback()
            }else{
              callback('请输入正确的手机号')
            }},
            trigger: "blur"
          }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 12, message: "请输入6至12位的密码", trigger: "blur" }
        ],
        code: [
          { required: true, message: "请输入图形验证码", trigger: "blur" },
          {
            min: 4,
            max: 4,
            message: "请输入4位数的图形验证码",
            trigger: "bblur"
          }
        ],
        rcode: [
          { required: true, message: "请输入验证码", trigger: "blur" },
          { min: 4, max: 4, message: "请输入4位数的验证码", trigger: "bblur" }
        ]
      }
    };
  },
  watch:{
    show(newVal){
      if (newVal == false){
        this.$refs.form.resetFields()
        this.imageUrl=''
        this.refresh()
      }
    }
  },
  methods: {
    handleRemove(file) {
      console.log(file);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleDownload(file) {
      console.log(file);
    },
    //验证头像的格式与大小
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      // return isJPG;
      return isJPG && isLt2M;
      //
    },
    //成功上传头像的操作
    handleAvatarSuccess(res) {
      this.imageUrl = process.env.VUE_APP_URL + '/' + res.data.file_path;
      this.form.avatar = res.data.file_path;
      this.$refs.form.validateField('avatar',error=>{
        window.console.log(error)
      })
      // this.imageUrl = URL.createObjectURL(file.raw);
    },
    toRegister(){
      this.$refs.form.validate(result=>{
        if (!result){
          this.$message.warning('请完整填写信息')
          return
        }else{
          register(this.form).then(()=>{
            // if(res.data.code == 200){
              this.$message.success('注册成功')
              this.show = false
            // }else{
            //   this.$message.error('注册失败')

            // }
          })
        }
        })},
    //获取短信验证码
    getCode(){
      let _isPass = 0;
      this.$refs.form.validateField(['phone','code'],error=>{
        if(!error){
          _isPass++
        }
      });
          //控制点击频率
          this.totalTime--
        let inter = setInterval(()=>{
          this.totalTime--;
          if(this.totalTime <= 0){
            clearInterval(inter)
            this.totalTime = 60
          }
        },1000)
      if(_isPass == 2){
        sendsms({
          phone:this.form.phone,
          code:this.form.code
        }).then(res=>{
          this.$message.success(res.data.captcha + '')
        })
    }},
  //刷新图形码
    refresh(){
      this.codeImg = process.env.VUE_APP_URL + '/captcha?type=sendsms&rrr='+ Date.now()
    }
    
  
}}
</script>

<style lang='less'>
.register {
  padding: 0 30px 0 26px;
  .top {
    height: 53px;
    background: linear-gradient(to right, #01c5fa, #1296fa);
    font-size: 14px;
    color: #fff;
    text-align: center;
    line-height: 53px;
  }
  .el-dialog__header {
    padding: 0;
  }
  .dialog-footer {
    text-align: center;
  }
  .row {
    .img {
      width: 100%;
      height: 40px;
    }
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .avatar-uploader {
    text-align: center;
  }
}
</style>